package com.donfelix.looknews.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.donfelix.looknews.R;
import com.donfelix.looknews.bean.zhihu.ZhihuDaily;
import com.donfelix.looknews.bean.zhihu.ZhihuDailyItem;
import com.donfelix.looknews.common.BaseFragment;
import com.donfelix.looknews.common.Config;
import com.donfelix.looknews.util.DBUtils;
import com.donfelix.looknews.util.UIUtils;
import com.donfelix.looknews.view.activity.ZhihuDailyDetailActivity;
import com.donfelix.looknews.view.adapter.ZhihuAdapter;
import com.donfelix.looknews.view.implpresenter.ZhihuPresenterImpl;
import com.donfelix.looknews.view.implview.IZhihuFragment;
import com.donfelix.looknews.view.implview.IZhihuPresenter;
import com.donfelix.looknews.view.implview.OnRecyclerViewItemClickLinstener;
import com.donfelix.looknews.widget.GridItemDividerDecoration;
import com.donfelix.looknews.widget.WrapContentLinearLayoutManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Don on 2017/3/27.
 * Desc
 */

public class ZhihuFragment extends BaseFragment implements IZhihuFragment, OnRecyclerViewItemClickLinstener {

    @BindView(R.id.recycler_zhihu)
    RecyclerView recyclerZhihu;
    @BindView(R.id.prograss)
    ProgressBar prograss;
    @BindView(R.id.stub_no_connection_text)
    ViewStub noConnectionText;
    @BindView(R.id.stub_posting_progress)
    ViewStub postingProgress;

    Unbinder unbinder;
    private boolean connect;
    private TextView noConnecText;
    private ConnectivityManager.NetworkCallback callback;
    private boolean monitorConnectivity;
    private IZhihuPresenter zhihuPresenter;
    private ZhihuAdapter adapter;
    private boolean loading;
    private String currentLoadDate;
    private LinearLayoutManager linearLayoutManager;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        setRetainInstance(true);//允许fragment跳过销毁和重新创建的周期
        View view = inflater.inflate(R.layout.fragment_zhihu, container, false);
        checkConnectivity();
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        zhihuPresenter = new ZhihuPresenterImpl(getContext(), this);
        adapter = new ZhihuAdapter(getContext());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            linearLayoutManager = new WrapContentLinearLayoutManager(getContext());
        } else {
            linearLayoutManager = new LinearLayoutManager(getContext());
        }
        recyclerZhihu.setLayoutManager(linearLayoutManager);
        recyclerZhihu.setHasFixedSize(true);
        recyclerZhihu.addItemDecoration(new GridItemDividerDecoration(getContext(), R.dimen.divider_height, R.color.divider));
        recyclerZhihu.setItemAnimator(new DefaultItemAnimator());
        recyclerZhihu.setAdapter(adapter);
        recyclerZhihu.addOnScrollListener(loadingMoreListener);
        adapter.setOnRecyclerViewItemClickLinstener(this);
        if (connect) {
            loadDate();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            callback = new ConnectivityManager.NetworkCallback() {
                @Override
                public void onAvailable(Network network) {
                    super.onAvailable(network);
                    connect = true;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            noConnectionText.setVisibility(View.GONE);
                            loadDate();
                        }
                    });
                }

                @Override
                public void onLost(Network network) {
                    super.onLost(network);
                    connect = false;
                }
            };
        }
    }

    private RecyclerView.OnScrollListener loadingMoreListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (dy > 0) {//向下滚动
                int visibleItemCount = linearLayoutManager.getChildCount();
                int totalItemCount = linearLayoutManager.getItemCount();
                int pastVisiblesItems = linearLayoutManager.findFirstVisibleItemPosition();
                if (!loading && (visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                    loading = true;
                    loadMoreDate();
                }
            }
        }
    };

    private void loadDate() {
        if (adapter.getItemCount() > 0) {
            adapter.clearData();
        }
        currentLoadDate = "0";
        zhihuPresenter.getLatestZhihuNews();
    }

    private void loadMoreDate() {
        adapter.loadingStart();
        zhihuPresenter.getTheDauly(currentLoadDate);
    }

    private void checkConnectivity() {
        ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        connect = networkInfo.isConnected() && networkInfo != null;
        if (!connect && prograss != null) {//不判断容易抛出空指针异常
            prograss.setVisibility(View.VISIBLE);
            if (noConnecText == null) {
                //noConnecText = (TextView) noConnectionText.findViewById(R.id.no_connect_text);
                noConnecText = (TextView) noConnectionText.inflate();
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                manager.registerNetworkCallback(new NetworkRequest.Builder()
                        .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build(), callback);
                monitorConnectivity = true;
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (monitorConnectivity) {
            ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                manager.unregisterNetworkCallback(callback);
            }
            monitorConnectivity = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        zhihuPresenter.unsubscribe();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void showProgressDialog() {
        if (prograss != null) {
            prograss.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideProgressDialog() {
        if (prograss != null) {
            prograss.setVisibility(View.GONE);
        }
    }

    @Override
    public void showError(String error) {
        if (recyclerZhihu != null) {
            Snackbar.make(recyclerZhihu, R.string.snack_infor, Snackbar.LENGTH_SHORT)
                    .setAction(R.string.try_again, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (currentLoadDate == "0") {
                                zhihuPresenter.getLatestZhihuNews();
                            } else {
                                zhihuPresenter.getTheDauly(currentLoadDate);
                            }
                        }
                    }).show();
        }
    }

    @Override
    public void updateList(ZhihuDaily daily) {
        if (loading) {
            loading = false;
            adapter.loadingFinished();
        }
        currentLoadDate = daily.getDate();
        adapter.addItems(daily.getStories());
        adapter.addBannerItems(daily.getTop_stories());
        if (!recyclerZhihu.canScrollVertically(View.SCROLL_INDICATOR_BOTTOM)) {
            loadMoreDate();
        }
    }

    @Override
    public void onItemClick(ZhihuAdapter.ZhihuViewHolder holder, ZhihuDailyItem dailyItem) {
        DBUtils.getDB(getActivity()).insertHasRead(Config.ZHIHU, dailyItem.getId(), 1);
        holder.text.setTextColor(Color.GRAY);
        Intent intent = new Intent(getActivity(), ZhihuDailyDetailActivity.class);
        intent.putExtra("id", dailyItem.getId());
        intent.putExtra("title", dailyItem.getTitle());
        UIUtils.startActivity(intent);
    }

    @Override
    public void onItemClick(ZhihuAdapter.BannerHeaderViewHolder holder, ZhihuDailyItem item) {
        Intent intent = new Intent(getActivity(), ZhihuDailyDetailActivity.class);
        intent.putExtra("id", item.getId());
        intent.putExtra("title", item.getTitle());
        UIUtils.startActivity(intent);
    }
}
